package com.hmy.infrastructure.service.signature.impl;

import com.fasc.open.api.bean.common.OpenId;
import com.fasc.open.api.exception.ApiException;
import com.fasc.open.api.v5_1.client.*;
import com.hmy.infrastructure.common.properties.FadadaProperties;
import com.hmy.infrastructure.common.constant.InfrastructureConstant;
import com.hmy.infrastructure.common.constant.RedisKeyConstant;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author seven.qi
 * @Date 2023/11/24 10:41
 * @Version 1.0
 */
@Service
@Slf4j
@Getter
public class FadadaBaseSignatureService {

    @Resource
    protected FadadaProperties fadadaProperties;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private OpenApiClient openApiClient;

    @Resource
    private ServiceClient serviceClient;

    @Resource
    private DocClient docClient;

    @Resource
    private UserClient userClient;

    @Resource
    private CorpClient corpClient;

    @Resource
    private OrgClient orgClient;

    @Resource
    private SealClient sealClient;

    @Resource
    private TemplateClient templateClient;

    @Resource
    private SignTaskClient signTaskClient;

    @Resource
    private EUIClient euiClient;

    protected OpenId getOpenId() {
        return OpenId.getInstance(InfrastructureConstant.CORP, fadadaProperties.getOpenCorpId());
    }

    protected String getOpenCorpId() {
        return fadadaProperties.getOpenCorpId();
    }

    protected String getClientCorpId(){
        return fadadaProperties.getClientCorpId();
    }

    protected String getCorpName() {
        return fadadaProperties.getCorpName();
    }

    protected String getToken() throws ApiException {
        // 获取缓存中的token
        String redisCacheToken = redisTemplate.opsForValue().get(RedisKeyConstant.FADADA_TOKEN);
        if (StringUtils.isNotEmpty(redisCacheToken)) {
            log.warn("get token from redis {}", redisCacheToken);
            return redisCacheToken;
        }
        String token = getServiceClient().getAccessToken().getData().getAccessToken();
        log.info("get token from fadada success, token : {}", token);
        redisTemplate.opsForValue().set(RedisKeyConstant.FADADA_TOKEN, token, 3600, TimeUnit.SECONDS);
        return token;
    }
}
